import { get, getCookie, remove, set } from './utils/stoage'
import http from './http'
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    subject: get('subject')
  },
  mutations: {
    increment (state) {
      state.count++
    },
    logout (state) {
      state.subject = null
      remove('subject')
    },
    login (state, o) {
      state.subject = o
      http.signature({token: o.token})
      set('subject', o)
    }
  },
  actions: {
    fetch ({commit}) {
      http.post('/user/getUserInfo').then(res => commit('login', res))
    },
    refresh ({commit}) {
      var signature = getCookie('signature', true)
      http.signature(signature)
      if (signature && signature.token) {
        store.dispatch('fetch')
      } else {
        commit('logout')
      }
    },
    toggle ({commit, state}, {value}) {
      document.body.classList.toggle(value)
    }
  }
})

window.addEventListener('hashchange', function () {
  var hash = location.hash.substr(1)
  if (hash) {
    var [name, value] = hash.split('=')
    store.dispatch(name, {value})
    history.back()
  }
})

export default store
